<?php

namespace frontend\modules\user\models;

use Yii;
use yii\base\Model;
use common\models\user\UserAddress;
use common\exceptions\ModelHttpException;

class AddressForm extends Model {

    /**
     * @name $user_id
     * @var integer 用户UID
     */
    public $user_id;

    /**
     * @name $name
     * @var string 收货人姓名
     */
    public $name;

    /**
     * @name $tel
     * @var string 收货人手机号
     */
    public $tel;

    /**
     * @name $province
     * @var string 省份
     */
    public $province;

    /**
     * @name $city
     * @var string 城市
     */
    public $city;

    /**
     * @name $county
     * @var string 区县
     */
    public $county;

    /**
     * @name $address_detail
     * @var string 详细地址
     */
    public $address_detail;

    /**
     * @name $area_code
     * @var string 地区编码，通过省市区选择获取
     */
    public $area_code;

    /**
     * @name $postal_code
     * @var string 邮政编码
     */
    public $postal_code;

    /**
     * @name $is_default
     * @var boolean 是否为默认地址
     */
    public $is_default = 0;

    /**
     * @name $_model
     */
    private $_model = null;

    public function __construct($id = 0, $config = array()) {
        parent::__construct($config);
        if ($id) {
            $this->_model = UserAddress::findOne($id);
            if (!$this->_model) {
                throw new ModelHttpException('地址信息不存在！');
            }
        }
    }

    public function rules() {
        return [
            [['user_id'], 'integer'],
            [['name', 'tel', 'province', 'city', 'county', 'address_detail'], 'required'],
            [['area_code', 'postal_code'], 'string', 'max' => 6],
            ['is_default', 'boolean', 'trueValue' => true, 'falseValue' => false, 'strict' => true],
            ['tel', '\common\validators\MobileValidator'],
        ];
    }

    /**
     * 保存动态信息（发布&修改）
     * @param [type] $data
     * @return void
     */
    public function save() {
        if (!$this->validate()) {
            throw new ModelHttpException('提交失败', $this->getFirstErrors());
        }
        $model = $this->_model;
        if ($model == null) {
            $model = new UserAddress();
        }
        $model->attributes = [
            'user_id' => $this->user_id,
            'name' => $this->name,
            'mobile' => $this->tel,
            'province' => $this->province,
            'city' => $this->city,
            'district' => $this->county,
            'address_detail' => $this->address_detail,
            'area_code' => $this->area_code,
            'postal_code' => $this->postal_code,
            'is_default' => $this->is_default ? 1 : 0,
        ];
        if (!$model->save()) {
            throw new ModelHttpException('收件地址保存失败！', $model->getFirstErrors());
        }

        return $model;
    }

}
